package com.epfresh.supplier.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aigestudio.wheelpicker.WheelPicker;
import com.epfresh.api.constant.AppSupplyRouterConstant;
import com.epfresh.api.entity.FileUploadResponse;
import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.DataManager;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.http.RequestManager;
import com.epfresh.api.ucrop.PhotoCore;
import com.epfresh.api.universalimageloader.core.DisplayImageOptions;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.assist.ImageSize;
import com.epfresh.api.universalimageloader.core.imageaware.ImageViewAware;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.api.utils.IDCard;
import com.epfresh.api.utils.L;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.utils.VerificationUtils;
import com.epfresh.api.widget.CommonInputItem;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.CertInfo;
import com.epfresh.supplier.entity.LocalUploadFileEntity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EnsurePersonActivity extends BaseActivity implements PhotoCore.PhotoResult {
    /*	@ViewInject(R.id.person)
        private TextView personTv;*/
    private ImageView person_fr;
    private ImageView person_back;
    private ImageView person_together;
    private TextView tvBtn;
    private TextView tvCache;
//    private EditText name;
//    private TextView number;

    CommonInputItem ciName;
    CommonInputItem ciId;
    CommonInputItem ciTraceId;


    private RelativeLayout rlPersonFr;

    private RelativeLayout rlPersonBack;
    private RelativeLayout rlPersonTogether;

    private View pbFr;
    private View pbBack;
    private View pbTogether;

    private View rlErrorFr;
    private View rlErrorBack;
    private View rlErrorTogether;


    private int imgWidth;
    private int imgHeight;
    private PhotoCore photoCore;
    private String fileFrPath = FileUtil.getImgCacheDir() + "/" + "fr";
    private String fileBackPath = FileUtil.getImgCacheDir() + "/" + "back";
    private String fileTogetherPath = FileUtil.getImgCacheDir() + "/" + "together";
    private String filePath;
    private ImageView currentIv;

    DisplayImageOptions displayImageOptions;

    private View rlRefuse;
    private View rlBottom;
    private TextView tvRefuseContent;
    boolean isFirst;
    String certStatus;
    View vWarning;
    private LinearLayout llChooseType;
    private String remark;
    private BottomSheetDialog bottomSheetCompany;
    private List<String> typeList = new ArrayList<>();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState != null) {
            getIntent().putExtra("isFirst", savedInstanceState.getBoolean("isFirst"));
            getIntent().putExtra("certInfo", savedInstanceState.getString("certInfo"));
            getIntent().putExtra("certType", savedInstanceState.getString("certType"));
            getIntent().putExtra("merchantId", savedInstanceState.getString("merchantId"));
        }
        initBottomSheetUnitDialog();
        isFirst = getIntent().getBooleanExtra("isFirst", false);
        certStatus = getIntent().getStringExtra("certType");
        remark = getIntent().getStringExtra("remark");
        setContentView(R.layout.activity_ensure_person);

        ciName = (CommonInputItem) findViewById(R.id.ci_name);
        ciTraceId = (CommonInputItem) findViewById(R.id.ci_trace_id);
        ciId = (CommonInputItem) findViewById(R.id.ci_id_card);
        llChooseType = findViewById(R.id.ll_choose_type);
        llChooseType.setOnClickListener(this);

        person_fr = (ImageView) findViewById(R.id.person_fr);
        person_back = (ImageView) findViewById(R.id.person_back);
        person_together = (ImageView) findViewById(R.id.person_together);
//        name = (EditText) findViewById(R.id.name);
//        number = (TextView) findViewById(R.id.number);
        rlPersonFr = (RelativeLayout) findViewById(R.id.rl_person_fr);
        rlPersonBack = (RelativeLayout) findViewById(R.id.rl_person_back);
        rlPersonTogether = (RelativeLayout) findViewById(R.id.rl_person_together);
        pbFr = findViewById(R.id.pb_fr);
        pbBack = findViewById(R.id.pb_back);
        pbTogether = findViewById(R.id.pb_together);
        rlErrorFr = findViewById(R.id.rl_error_fr);
        rlErrorBack = findViewById(R.id.rl_error_back);
        rlErrorTogether = findViewById(R.id.rl_error_together);
        tvBtn = (TextView) findViewById(R.id.tv_btn);
        rlRefuse = findViewById(R.id.rl_refuse_reason);
        tvRefuseContent = (TextView) findViewById(R.id.tv_refuse_content);
        vWarning = findViewById(R.id.ll_warning_ensure);
        basetitle.setText("申请开店");
        baseback.setVisibility(View.VISIBLE);

        fileFrPath = fileFrPath + "_" + getUser().getAccountId();
        fileBackPath = fileBackPath + "_" + getUser().getAccountId();
        fileTogetherPath = fileTogetherPath + "_" + getUser().getAccountId();


        imgWidth = (LocalDisplay.SCREEN_WIDTH_PIXELS - LocalDisplay.dp2px(48)) / 2;
        imgHeight = imgWidth * 204 / 282;
        reSizeIv(rlPersonFr);
        reSizeIv(rlPersonBack);
        reSizeIv(rlPersonTogether);
        reSizeIv(findViewById(R.id.rl_tips));

        photoCore = new PhotoCore(this, this);
        photoCore.setCrop(false);
        photoCore.setRatio(4, 3);
        photoCore.setResultHeight(1500);
        photoCore.setResultWidth(1500);
//        loadImage(Uri.fromFile(new File(fileFrPath)).toString(), person_fr);
//        loadImage(Uri.fromFile(new File(fileBackPath)).toString(), person_back);
//        loadImage(Uri.fromFile(new File(fileTogetherPath)).toString(), person_together);
//        loadPicInfo();
//        updateInfo();
        person_back.setOnClickListener(this);
        person_fr.setOnClickListener(this);
        person_together.setOnClickListener(this);
        tvBtn.setOnClickListener(this);
        rightbtn.setText(getString(R.string.help));
        rightbtn.setVisibility(View.VISIBLE);
        rightbtn.setTextColor(0xff898989);
        rightbtn.setOnClickListener(this);
        tvCache = (TextView) findViewById(R.id.tv_save_cache);
        tvCache.setOnClickListener(this);
        rlBottom = findViewById(R.id.v_bottom);
        CertInfo ci = null;
        if (isFirst) {
            ci = DataManager.getInstance().getCertInfo();
            Log.e("certInfo", "getCertInfo:" + ci);
            initData(ci);
        } else {
            String certInfo = getIntent().getStringExtra("certInfo");
            if (certInfo != null) {
                ci = new Gson().fromJson(certInfo, CertInfo.class);
            }
            initData(ci);
            //审核中
            if ("1".equals(certStatus)) {
                certIng();
                vWarning.setVisibility(View.VISIBLE);
                vWarning.setOnClickListener(this);
                findViewById(R.id.pb_together_add).setVisibility(View.INVISIBLE);
                findViewById(R.id.pb_back_add).setVisibility(View.INVISIBLE);
                findViewById(R.id.pb_fr_add).setVisibility(View.INVISIBLE);
            } else if ("3".equals(certStatus)) {//认证失败
                certFail();
                requestCertificateRefuse();
            } else if ("2".equals(certStatus)) {//认证成功
                certSucceed();
                vWarning.setVisibility(View.VISIBLE);

                vWarning.setOnClickListener(this);
                findViewById(R.id.pb_together_add).setVisibility(View.INVISIBLE);
                findViewById(R.id.pb_back_add).setVisibility(View.INVISIBLE);
                findViewById(R.id.pb_fr_add).setVisibility(View.INVISIBLE);
            } else {
                //   certUn();
            }
        }


    }

    //审核中
    public void certIng() {
        rlBottom.setVisibility(View.GONE);

        ciId.setEditable(false);
        ciTraceId.setEditable(false);
        ciName.setEditable(false);
    }

    //审核失败
    public void certFail() {
        rlBottom.setVisibility(View.VISIBLE);
        tvCache.setVisibility(View.GONE);
        tvBtn.setText("重新提交");

    }

    //审核成功
    public void certSucceed() {
        rlBottom.setVisibility(View.GONE);
        ciId.setEditable(false);
        ciTraceId.setEditable(false);
        ciName.setEditable(false);
    }

    //未审核
    public void certUn() {
        rlBottom.setVisibility(View.VISIBLE);
        tvCache.setVisibility(View.GONE);
        tvBtn.setText("提交");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("certInfo", getIntent().getStringExtra("certInfo"));
        outState.putString("certType", getIntent().getStringExtra("certType"));
        outState.putString("merchantId", getIntent().getStringExtra("merchantId"));
        outState.putBoolean("isFirst", getIntent().getBooleanExtra("isFirst", false));
        super.onSaveInstanceState(outState);
    }

    public void initData(CertInfo certInfo) {
        if (certInfo != null && "0".equals(certInfo.getType())) {

            ciName.setContentText(certInfo.getName());
            ciName.setSelectionLast();
            ciId.setContentText(certInfo.getIdCardNo());
            ciTraceId.setContentText(certInfo.getTraceCardNo());
            picId1 = certInfo.getIdCardObverseImgId();
            picId2 = certInfo.getIdCardReverseImgId();
            picId3 = certInfo.getIdCardWithPersonImgId();
            loadImage(certInfo.getIdCardObverseImgUrl(), person_fr);
            loadImage(certInfo.getIdCardReverseImgUrl(), person_back);
            loadImage(certInfo.getIdCardWithPersonImgUrl(), person_together);
        }
        if (!TextUtils.isEmpty(remark)) {
            tvRefuseContent.setText(remark);
            rlRefuse.setVisibility(View.VISIBLE);
        }
    }

    public void reSizeIv(View iv) {
        ViewGroup.LayoutParams lp = iv.getLayoutParams();
        lp.height = imgHeight;
        lp.width = imgWidth;

        iv.setLayoutParams(lp);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.ll_choose_type:
                if (!TextUtils.isEmpty(remark)) {
                    T.toast("如需修改，请联系客服：400-0588-198");
                    break;
                }
                showUnit();
                break;
            case R.id.person_fr:
                filePath = fileFrPath;
                currentIv = person_fr;

                if ("1".equals(certStatus)) {//认证中
                    toast("认证中，不能修改");
                } else if ("2".equals(certStatus)) {
                    toast("已认证");
                } else {//认证失败
                    photoCore.showPhotoDialog(Uri.fromFile(new File(filePath)), filePath, rlErrorFr.getVisibility() != View.GONE);
                }
                break;
            case R.id.person_back:
                filePath = fileBackPath;
                currentIv = person_back;
                if ("1".equals(certStatus)) {//认证中
                    toast("认证中，不能修改");
                } else if ("2".equals(certStatus)) {
                    toast("已认证");
                } else {//认证失败
                    photoCore.showPhotoDialog(Uri.fromFile(new File(filePath)), filePath, rlErrorBack.getVisibility() != View.GONE);
                }

                break;
            case R.id.person_together:
                filePath = fileTogetherPath;
                currentIv = person_together;
                if ("1".equals(certStatus)) {//认证中
                    toast("认证中，不能修改");
                } else if ("2".equals(certStatus)) {
                    toast("已认证");
                } else {//认证失败
                    photoCore.showPhotoDialog(Uri.fromFile(new File(filePath)), filePath, rlErrorTogether.getVisibility() != View.GONE);
                }

                break;


            case R.id.baseback:
                // 返回上一页
                finish();
                break;
            case R.id.rightbtn:
                help();
                break;
            case R.id.tv_save_cache:
                saveCache();
                break;
            case R.id.tv_btn:

                String name = ciName.getContentText();
                if (name == null || "".equals(name)) {
                    toast("请填写您的真实姓名");
                    return;
                }
                if (!VerificationUtils.isValid(name)) {
                    toast(getString(R.string.illegal_input, "真实姓名"));
                    return;
                }
                String id = ciId.getContentText();
                if (id == null || "".equals(id)) {
                    toast("请填写您的身份证号");
                    return;
                }

                IDCard idCard = new IDCard();//检验身份证号，工具类  当前仅校验位数
                String s = idCard.IDCardValidate(ciId.getContentText().toLowerCase());
                if ("".equals(s)) {
                } else {
                    toast(s);
                    return;
                }

                if (!TextUtils.isEmpty(ciTraceId.getContentText()) && ciTraceId.getContentText().length()
                        != 13) {
                    toast("请输入合法的流通追溯号");
                    return;

                }
                if (TextUtils.isEmpty(picId1)) {
                    toast("请上传身份证正面照");
                    return;
                }
                if (TextUtils.isEmpty(picId2)) {
                    toast("请上传身份证反面照");
                    return;
                }
                if (TextUtils.isEmpty(picId3)) {
                    toast("请上传本人手持身份证照");
                    return;
                }

                if (picId1 != null && !picId1.equals("") && picId2 != null && !picId2.equals("") && picId3 != null && !picId3.equals("")) {

                    requestCertificate(false);
                    return;
                }

                break;

            case R.id.ll_warning:
                intoPhone();
                break;
        }
    }

    private void intoPhone() {
        String servicePhone = BaseApplication.getDoc().getServicePhone();
        String[] split = servicePhone.split("：");
        if (split == null || split.length < 2) {
            split = servicePhone.split(":");
        }
        if (split != null && split.length > 1) {
            String s = split[split.length - 1];
            s = s.replace("-", "");
            s.replace("－", "");
            if (VerificationUtils.isNumeric(s)) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + s));//调出来拨打页面；
                startActivity(intent);
            }
        }
    }

    private void saveCache() {
        if (isContentEmpty()) {
            toast("请填写信息");
            return;
        }
        requestCertificate(true);
    }

    private boolean isContentEmpty() {

        if (!TextUtils.isEmpty(ciId.getContentText())) {
            return false;
        }

        if (!TextUtils.isEmpty(ciName.getContentText())) {
            return false;
        }

        if (!TextUtils.isEmpty(ciTraceId.getContentText())) {
            return false;
        }


        return true;
    }


    private void help() {

        Intent intent = new Intent(this, WebActivity.class);
        intent.putExtra(Constant.KEY_WEB_URL, Constant.URL_HELP_CERTIFY);
        intent.putExtra(Constant.KEY_WEB_TITLE, getString(R.string.help));
        startActivity(intent);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        // 用户没有进行有效的设置操作，返回
        if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplication(), "取消", Toast.LENGTH_LONG).show();
            return;
        }
        photoCore.onResult(requestCode, resultCode, intent);
        super.onActivityResult(requestCode, resultCode, intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        photoCore.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    String accountId = "";
    String token = "";
    String picId1 = "", picId2 = "", picId3 = "";


    private DisplayImageOptions getImageOption() {
        if (displayImageOptions == null)
            displayImageOptions = new DisplayImageOptions.Builder()
                    .cacheInMemory(false)// 设置下载的图片是否缓存在内存中

                    .cacheOnDisk(false)// 设置下载的图片是否缓存在SD卡中
                    .considerExifParams(true) // 是否考虑JPEG图像EXIF参数（旋转，翻转）
                    // .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//
                    // 设置图片以如何的编码方式显示
                    .bitmapConfig(Bitmap.Config.RGB_565)// 设置图片的解码类型//
                    // .decodingOptions(new Options())//设置图片的解码配置
                    // .delayBeforeLoading(int delayInMillis)//int
                    // delayInMillis为你设置的下载前的延迟时间
                    // 设置图片加入缓存前，对bitmap进行设置
                    // .preProcessor(BitmapProcessor preProcessor)
                    .resetViewBeforeLoading(true)// 设置图片在下载前是否重置，复位
                    .build();// 构建完成
        return displayImageOptions;
    }

    public void loadImage(String path, ImageView iv) {
        ImageSize imageSize = new ImageSize(imgWidth, imgHeight);
        ImageLoader.getInstance().displayImage(path, new ImageViewAware(iv), getImageOption(), imageSize, null, null);

    }

    private void showProgress(int action) {
        switch (action) {
            case R.id.person_fr:
                pbFr.setVisibility(View.VISIBLE);
                break;
            case R.id.person_back:
                pbBack.setVisibility(View.VISIBLE);
                break;
            case R.id.person_together:
                pbTogether.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }
    }

    private void hideProgress(int action) {
        switch (action) {
            case R.id.person_fr:
                pbFr.setVisibility(View.GONE);
                break;
            case R.id.person_back:
                pbBack.setVisibility(View.GONE);
                break;
            case R.id.person_together:
                pbTogether.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    private void showError(int action) {
        switch (action) {
            case R.id.person_fr:
                rlErrorFr.setVisibility(View.VISIBLE);
                break;
            case R.id.person_back:
                rlErrorBack.setVisibility(View.VISIBLE);
                break;
            case R.id.person_together:
                rlErrorTogether.setVisibility(View.VISIBLE);
                break;
            default:
                break;
        }

    }

    private void hideError(int action) {
        switch (action) {
            case R.id.person_fr:
                rlErrorFr.setVisibility(View.GONE);
                break;
            case R.id.person_back:
                rlErrorBack.setVisibility(View.GONE);
                break;
            case R.id.person_together:
                rlErrorTogether.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    RequestTag tag = new RequestTag();

    OnRequestListener<FileUploadResponse> uploadListener = new OnRequestListener<FileUploadResponse>() {
        @Override
        public FileUploadResponse jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, FileUploadResponse.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

            RequestTag requestTag = (RequestTag) tag;
            hideProgress(requestTag.action);
            showError(requestTag.action);
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            hideProgress(requestTag.action);
            showError(requestTag.action);
        }

        @Override
        public void onStart(Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            showProgress(requestTag.action);
            hideError(requestTag.action);
        }

        @Override
        public void onResponse(ResponseEntity<FileUploadResponse> response, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            hideProgress(requestTag.action);
            FileUploadResponse responseElement = response.getResponseElement();
            int id = responseElement.getId();
            if (id == Integer.MIN_VALUE) {
                toast("图片上传失败");
                return;
            }
            File f = null;
            switch (requestTag.action) {
                case R.id.person_fr:
                    picId1 = id + "";
                    f = new File(fileFrPath);
                    updatePicInfo(f, id, "person_fr_" + getUser().getAccountId());
                    break;
                case R.id.person_back:
                    picId2 = id + "";
                    f = new File(fileBackPath);
                    updatePicInfo(f, id, "person_back_" + getUser().getAccountId());
                    break;
                case R.id.person_together:
                    picId3 = id + "";
                    f = new File(fileTogetherPath);
                    updatePicInfo(f, id, "person_together_" + getUser().getAccountId());
                    break;
                default:
                    break;
            }
        }
    };

    public void uploadImage(String filePath, int id) {

        try {
            String file = FileUtil.encodeBase64File(filePath);
            RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
            //data.setCmd("file/upload");
            data.setCmd(AppSupplyRouterConstant.cmd_account_file_upload);
            //data.setToken(getUser().getToken());

            data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
            Map<String, String> map = new HashMap<>();
            map.put("ext", "jpg");
            map.put("file", file);

            data.setParameters(map);


            tag.tag = AppSupplyRouterConstant.cmd_account_file_upload;
            tag.action = id;
            request(data, tag, uploadListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    OnRequestListener<CertInfo> onResquestListener = new OnRequestListener<CertInfo>() {
        @Override
        public CertInfo jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, CertInfo.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<CertInfo> response, Object tag) {
            hideProgressDialog();
            CertInfo responseElement = response.getResponseElement();
            if (responseElement != null && responseElement.isSuccess()) {
                DataManager.getInstance().setCertInfo(responseElement);
                boolean isScratch = false;
                if (tag != null && tag instanceof RequestTag) {
                    RequestTag rt = (RequestTag) tag;
                    isScratch = rt.type == 0 ? false : true;

                }
                if (isFirst && !isScratch) {
                    intoBank();
                } else if (isFirst && isScratch) {
                    toast("保存成功");
                } else {
                    intoStoreEnsureAndOpen();
                }

            } else {
                toast("提交失败");
            }
        }
    };

    public void intoBank() {
        Intent intent = new Intent(this, BankActivity.class);

        intent.putExtra(Constant.TYPE, -1);
        intent.putExtra("card_count", getStoreInfo().getBankCardCount());
        intent.putExtra("userType", 1);
        intent.putExtra("isFirst", isFirst);
        intent.putExtra("remark", remark);
        startActivity(intent);
    }

    public void intoStoreEnsureAndOpen() {
        getStoreInfo().setCertStatus("1");
        updateStoreInfo(getStoreInfo());
        Intent intent = new Intent(this, StoreEnsureAndOpenActivity.class);
        startActivity(intent);
        finish();
    }

    public void requestCertificate(boolean isScratch) {

        String nameStr = ciName.getContentText();
        String numberStr = ciId.getContentText();

        RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
        //data.setCmd("account/personalCert");
        data.setCmd(AppSupplyRouterConstant.cmd_account_account_personalCert);
        //data.setToken(getUser().getToken());

        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        Map<String, String> map = new HashMap<>();

        map.put("name", nameStr);
        map.put("traceCardNo", ciTraceId.getContentText());


        if (isFirst) {
            map.put("status", "-1");
        }
        map.put("accountId", getUser().getAccountId());
        map.put("idCardNo", numberStr);
        map.put("idCardObverseImgId", picId1);
        map.put("idCardReverseImgId", picId2);
        map.put("idCardWithPersonImgId", picId3);
        map.put("merchantId", getIntent().getStringExtra("merchantId"));
        data.setParameters(map);
        RequestTag tag = new RequestTag();
        tag.tag = AppSupplyRouterConstant.cmd_account_account_personalCert;
        tag.type = isScratch ? 1 : 0;
        request(data, tag, onResquestListener);
    }

    public void saveInfo() {
        String nameStr = ciName.getContentText();
        String numberStr = ciId.getContentText();
        SharedPreferences sp = FileUtil.getSharedPreferences();
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("idCardNo_" + getUser().getAccountId(), numberStr);
        edit.putString("idName_" + getUser().getAccountId(), nameStr);
        edit.commit();
    }

    public void updateInfo() {
        SharedPreferences sp = FileUtil.getSharedPreferences();
        String nameStr = sp.getString("idName_" + getUser().getAccountId(), "");
        ciId.setContentText(sp.getString("idCardNo_" + getUser().getAccountId(), ""));
        ciName.setContentText(sp.getString("idName_" + getUser().getAccountId(), ""));

    }

    public void updatePicInfo(File f, int id, String key) {
        long lastModified = f.lastModified();
        long totalSpace = f.getTotalSpace();
        LocalUploadFileEntity localUploadFileEntity = new LocalUploadFileEntity();
        localUploadFileEntity.setId(id);
        localUploadFileEntity.setModified(lastModified);
        localUploadFileEntity.setTotalSpace(totalSpace);
        SharedPreferences sp = FileUtil.getSharedPreferences();
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(key, localUploadFileEntity.toString());
        edit.commit();
    }

    private void loadPicInfo() {
        SharedPreferences sp = FileUtil.getSharedPreferences();
        String result = sp.getString("person_fr_" + getUser().getAccountId(), "");
        picId1 = initPicId(result, fileFrPath, person_fr.getId());
        result = sp.getString("person_back_" + getUser().getAccountId(), "");
        picId2 = initPicId(result, fileBackPath, person_back.getId());
        result = sp.getString("person_together_" + getUser().getAccountId(), "");
        picId3 = initPicId(result, fileTogetherPath, person_together.getId());
    }

    private String initPicId(String result, String filePath, int id) {
        L.d("file", "" + filePath + "--result:" + result);
        File f = new File(filePath);
        if (!TextUtils.isEmpty(result)) {
            LocalUploadFileEntity localUploadFileEntity = LocalUploadFileEntity.getLocalUploadFileEntity(result);
            L.d("file", "---------");
            if (localUploadFileEntity != null) {
                boolean isUpload = localUploadFileEntity.isUpload(f.lastModified(), f.getTotalSpace());
                L.d("file", "1." + localUploadFileEntity.getModified() + "--" + localUploadFileEntity.getTotalSpace());
                L.d("file", "2." + f.lastModified() + "--" + f.getTotalSpace());
                if (isUpload) {
                    return localUploadFileEntity.getId() + "";
                }
            }
        }
        if (f.exists()) {
            showError(id);
        }

        return "";
    }


    @Override
    public void onSuccess(String path) {


        loadImage(path, currentIv);

        uploadImage(filePath, currentIv.getId());
    }

    @Override
    public void onFail(String msg) {
        toast("获取图片失败");
    }

    @Override
    public void onReupload() {
        uploadImage(filePath, currentIv.getId());
    }

    @Override
    protected void onDestroy() {
        if (photoCore != null) {
            photoCore.onDestory();
        }
//        saveInfo();
        RequestManager.getInstance().cancel(tag);
        RequestManager.getInstance().cancel("account/personalCert");
        super.onDestroy();
    }


    public void requestCertificateRefuse() {

        RequestEntitySupply<Map<String, String>> data = new RequestEntitySupply<>();
        data.setCmd(AppSupplyRouterConstant.cmd_account_account_certInfo);
        //data.setToken(getUser().getToken());
        RequestTag tag = new RequestTag();
        tag.type = RequestTag.TYPE_CURRENT;
        tag.tag = AppSupplyRouterConstant.cmd_account_account_certInfo;

        request(data, tag, new OnRequestListener<Map<String, String>>() {
            @Override
            public Map<String, String> jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, new TypeToken<Map<String, String>>() {
                }.getType());
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {

            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {

            }

            @Override
            public void onStart(Object tag) {

            }

            @Override
            public void onResponse(ResponseEntity<Map<String, String>> response, Object tag) {

                Map<String, String> responseElement = response.getResponseElement();

//                "remark": "", 拒绝原因
//                "status": 1, 审核状态
//                "type": 2 认证类型
                if (responseElement != null) {
                    String remark = responseElement.get("remark");
                    String type = responseElement.get("type");
                    if (remark != null && "1".equals(type)) {
                        tvRefuseContent.setText(remark);
                        rlRefuse.setVisibility(View.VISIBLE);
                    }
                }

            }
        });
    }

    private void initBottomSheetUnitDialog() {
        typeList.add("个人认证");
        typeList.add("企业认证");
        View view = View.inflate(this, R.layout.companytype, null);
        final WheelPicker wheelPicker = view.findViewById(R.id.main_wheel);
        TextView cancel = view.findViewById(R.id.tv_cancel);
        TextView define = view.findViewById(R.id.tv_define);
        wheelPicker.setData(typeList);
        bottomSheetCompany = new BottomSheetDialog(this);
        bottomSheetCompany.setCancelable(true);
        bottomSheetCompany.setContentView(view);
        bottomSheetCompany.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {

            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetCompany.dismiss();
            }
        });
        define.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetCompany.dismiss();
                if (typeList.get(wheelPicker.getCurrentItemPosition()).equals("企业认证")) {
                    Intent intent = new Intent(EnsurePersonActivity.this, EnsureCompanyActivity.class);
                    intent.putExtra("isFirst", isFirst);
                    intent.putExtra("remark", remark);
                    intent.putExtra("merchantId", getIntent().getStringExtra("merchantId"));
                    startActivity(intent);
                    finish();
                }
            }
        });
    }

    private void showUnit() {
        bottomSheetCompany.show();
    }
}
